package cn.ad.server.web.spring.service.httpclient.executor;

import cn.ad.server.web.log.IAdEventLogger;
import cn.ad.server.web.log.entity.AdTrafficHttpLog;
import cn.ad.server.web.spring.service.components.http.client.AdHttpGetRequest;
import cn.ad.server.web.spring.service.components.http.client.AdHttpPostRequest;
import cn.ad.server.web.spring.service.components.http.client.AdHttpRequest;
import cn.ad.server.web.spring.service.components.http.client.AdHttpResponse;
import cn.ad.server.web.spring.service.httpclient4.HttpClientExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @deprecated 此类不推荐使用。依赖于实现类HttpClientExecutor。导致强耦合。建议使用{@link HttpClientExtLogExecutor}
 * 使用httpclient4执行请求。
 * @author wangwei
 */

public class HttpClientLogExecutor extends HttpClientExecutor {
	private static Logger LOGGER = LoggerFactory.getLogger(HttpClientLogExecutor.class);
	/**
	 * Adserver 日志记录实现接口
	 */
	private IAdEventLogger adEventLogger;

	public IAdEventLogger getAdEventLogger() {
		return adEventLogger;
	}
	
	public void setAdEventLogger(IAdEventLogger adEventLogger) {
		this.adEventLogger = adEventLogger;
	}

	/**
	 * 请求后续执行
	 * @param <T>
	 * @param request
	 * @param response
	 */
	public <T> void doExecuteEnd(AdHttpGetRequest request,AdHttpResponse<T> response){
		logAdserverEventLog(request, response);
	}
	/**
	 * 请求后续执行
	 * @param <T>
	 * @param request
	 * @param response
	 */
	public <T> void doExecuteEnd(AdHttpPostRequest request,AdHttpResponse<T> response){
		logAdserverEventLog(request, response);
	}
	
	/**
	 * 记录广告事件日志
	 * @param request
	 * @param response
	 * @param time 请求响应时间（毫秒）。
	 */
	public void logAdserverEventLog(AdHttpGetRequest request,AdHttpResponse<?> response){
		AdTrafficHttpLog log = new AdTrafficHttpLog();
		log.setHttpMethod("GET");
		pupulateLog(request, response,log);
		adEventLogger.log(log);
		
	}
	
	/**
	 * 记录广告事件日志
	 * @param request
	 * @param response
	 * @param time 请求响应时间（毫秒）。
	 */
	public void logAdserverEventLog(AdHttpPostRequest request,AdHttpResponse<?> response){
		AdTrafficHttpLog log = new AdTrafficHttpLog();
		log.setHttpMethod("POST");
		pupulateLog(request, response, log);
		adEventLogger.log(log);
		
	}

	/**
	 * 填充log
	 * @param request
	 * @param response
	 * @param time
	 * @param log
	 */
	private void pupulateLog(AdHttpRequest request, AdHttpResponse<?> response, AdTrafficHttpLog log) {
		log.setRequstThreadName(Thread.currentThread().getName());
		log.setRequstTime(request.getRequstTime());
		log.setUrl(request.getUrl());
		log.setProtocol(response.getProtocol());
		log.setMajor(response.getMajor());
		log.setMinor(response.getMinor());
		log.setStatusCode(response.getStatusCode());
		log.setLength(response.getLength());
		log.setTime(response.getRespTime());
		LOGGER.debug(log.toString());
	}

	
	
}
